<!--
 * @Author: your name
 * @Date: 2020-05-25 10:49:09
 * @LastEditTime: 2020-06-03 15:19:41
 * @LastEditors: Please set LastEditors
 * @Description: In User Settings Edit
 * @FilePath: \mobile_project_0519\mobile_post\src\pages\login\login.vue
--> 
<template>
  <div class="login">
    <van-nav-bar title="登录" left-text="返回" left-arrow @click-left="onClickLeft" />

    <van-form @submit="onSubmit">
      <van-field
        v-model="loginForm.username"
        name="用户名"
        label="用户名"
        :rules="[{ required: true, message: '请填写用户名' }]"
      />
      <van-field
        v-model="loginForm.password"
        type="password"
        name="密码"
        label="密码"
        :rules="[{ required: true, message: '请填写密码' }]"
      />
      <div style="margin: 16px;">
        <van-button round block type="info" native-type="submit">登录</van-button>
      </div>
    </van-form>
  </div>
</template>

<script>
import * as api from "@/request/api/login.js"
import { createNamespacedHelpers } from "vuex"
const { mapMutations } = createNamespacedHelpers("userModule")
export default {
  data() {
    return {
      //登录表单对象
      loginForm: {
        username:"",
        password:""
      } 
    };
  },

  methods: {

    // 获取token密钥
    ...mapMutations(["GET_TOKEN"]),
    //...mapMutations(["GET_NAME"]),
    // 获取登录接口数据
    async API_login(name,pwd){
      let result = {
        name,
        pwd
      }
      return api.login(result)
    },

    //登录表单提交 
    async onSubmit(){
      let {username,password} = this.loginForm
      let res = await this.API_login(username,password)
      //console.log(res.config.data)

      // 存储token
      //localStorage.setItem("showToken",res.data.token)
      localStorage.setItem("getUser",res.config.data)
      //localStorage.setItem("getName",res.data.name)
      // 不使用辅助函数的写法
      //this.$store.commit("userModule/GET_TOKEN",res.data.token)
      
      if(res.data.code === 1000){
        // 使用辅助函数的写法
        this.GET_TOKEN(res.data.token)
        //this.GET_NAME(res.data.name)
        this.$eventBus.$emit("getUser",res.config.data)
        this.$toast.success("登录成功！")
        this.$router.push("/user")
      }else{
        this.$toast.fail("登录失败，请检查用户名和密码！")
      }
    },
    // 返回上一页
    onClickLeft() {
      this.$router.go(-1);
    }
  }
};
</script>

<style>
/* .login_contents {
  height: 220px;
  background-color: #f0f0f0;
  padding: 20px 4px 0 4px;
}
.login_user {
  margin-top: 10px; 
}
.login_pwd {
  margin-bottom: 8px;
} */
</style>